//
//  Upgrade.swift
//  
//  APP检测更新组件
//
//  Created by gongkai on 15/6/11.
//
//

import UIKit

class Upgrade: NSObject,UIAlertViewDelegate {
    private struct Static {
        static var onceToken : dispatch_once_t = 0
        static var staticInstance : Upgrade!
    }
    private static var _lookupUrl = "http://itunes.apple.com/lookup?id="
    private static var _updateUri = "itms-apps://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftwareUpdate?id=%@&mt=8"
    private let localVersion = NSBundle.mainBundle().infoDictionary![kCFBundleVersionKey as! String] as! String
    
    var appId:String!
    
    
    /// 新版本的版本号
    var version:String?
    /// 新版本的更新说明
    var releaseNotes:String?

    
    static func shareInstance() -> Upgrade{
        dispatch_once(&Static.onceToken) {
            Static.staticInstance = Upgrade()
        }

        return Static.staticInstance
    }
    
    
    /**
    检测更新
    
    :param: callback 回调，参数1为Bool，true为有新版本，否则无。如果有则参数2,3有值，参数2为新版本的版本号，参数3为更新说明
    */
    func check(callback:((Bool,String?,String?)->())?){
        if(appId==nil){
            if(callback != nil){
                callback!(false,nil,nil)
            }
            return
        }
        let url = Upgrade._lookupUrl + appId
        let request = NSURLRequest(URL:NSURL(string:url)!)
        
        weak var this = self
        
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response, data, error) -> Void in
            if(error == nil && data != nil){
                let jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves, error: nil)
                if let dict = jsonData as? NSDictionary{
                    if let results = dict["results"] as? NSArray where results.count > 0{
                        if let result = results[0] as? NSDictionary{
                            this!.version = result["version"] as? String
                            this!.releaseNotes = result["releaseNotes"] as? String
                             //判断是否一致
                            if(this!.version != this!.localVersion){
                                if(callback != nil){
                                    callback!(true,this!.version,this!.releaseNotes)
                                }else{
                                    UIAlertView(title: NSString(format: NSLocalizedString("发现新版本",comment:""), this!.version!) as String, message: this!.releaseNotes!, delegate: this!, cancelButtonTitle: NSLocalizedString("取消",comment:""), otherButtonTitles: NSLocalizedString("去更新",comment:"")).show()
                                }
                                return
                            }
                        }
                    }
                }
            }
            if(callback != nil){
                callback!(false,nil,nil)
            }
        }
    }
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if(buttonIndex == 1 ){
            self.update()
        }
    }
    
    /**
        去更新
    */
    func update(){
        UIApplication.sharedApplication().openURL(NSURL(string: NSString(format: Upgrade._updateUri, self.appId) as String)!)
    }
}
